package com.spzx.payment.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.spzx.common.core.web.controller.BaseController;
import com.spzx.common.core.web.domain.AjaxResult;
import com.spzx.common.security.annotation.RequiresLogin;
import com.spzx.payment.configure.AlipayConfig;
import com.spzx.payment.service.IAlipayService;
import com.spzx.payment.service.IPaymentInfoService;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/alipay")
public class AlipayController extends BaseController {

    @Autowired
    private IAlipayService alipayService;

    @Autowired
    private IPaymentInfoService paymentInfoService;

    /**
     * 向手机支付宝客户端发起支付请求。
     * <form name="punchout_form" method="post"
     * action="https://openapi.alipay.com/gateway.do?charset=utf-8&method=alipay.trade.wap.pay&sign=BlEpb%2F%2FVUmgcxjpob7RU4rG98ha2vUQAmeiGQ3fCjROA3ULv5gabOKB353oDOTQGlVAoA%2BJI20SodTW8DoE6GVn0uwBcC9Lb4T8W0w985sQPIj8YgxVLx%2Fzyp3H8JzjoGZ%2B1E50OcVWVvJ7XrwpQkdxgkQD702Eb%2FE0EsJHxj58bk0cVA%2Fx7WtxQFKxnna3XLrF%2BcC3WvO%2BJRrK9R51GsMEdsV71bOra2JnIdx0VSvDCVHjpO%2F4LOjpdNJgdovmGg4sF57Z2zxhJJOxtSNikFSrVtBDhadwoiN3YP0YHpzvl9fQtjpdLDkAM0XJuSu6StU7GJo3HhaBxXtYCS42LAg%3D%3D&return_url=http%3A%2F%2Fspzx0522.free.idcfengye.com%2Fpayment%2Falipay%2Fcallback%2Freturn&notify_url=http%3A%2F%2Fspzx0522.free.idcfengye.com%2Fpayment%2Falipay%2Fcallback%2Fnotify&version=1.0&app_id=2021001163617452&sign_type=RSA2&timestamp=2024-10-18+11%3A37%3A00&alipay_sdk=alipay-sdk-java-4.8.73.ALL&format=json">
     * <input type="hidden" name="biz_content" value="{&quot;out_trade_no&quot;:&quot;8ec0017171bd4ba0b4195add59fce0ef&quot;,&quot;total_amount&quot;:&quot;0.01&quot;,&quot;subject&quot;:&quot;小米 红米Note10 5G手机 白色 + 8G;&quot;,&quot;product_code&quot;:&quot;QUICK_WAP_WAY&quot;}">
     * <input type="submit" value="立即支付" style="display:none" >
     * </form>
     *
     *
     * @param orderNo
     * @return
     * @throws AlipayApiException
     */
    @Operation(summary = "支付宝下单")
    @RequiresLogin
    @RequestMapping("submitAlipay/{orderNo}")
    @ResponseBody
    public AjaxResult submitAlipay(@PathVariable(value = "orderNo") String orderNo) throws AlipayApiException {
        String form = alipayService.submitAlipay(orderNo);
        System.out.println("form = " + form); //返回给前端form表单(支付宝平台接口生成的)，用于打开手机上支付宝app，弹出支付密码框。
        return success(form);
    }


    /**
     * 支付宝同步回调
     *      这个地址会被调用多次，不用管几次；
     * @return
     */
    @RequestMapping("callback/return")
    public String callBack() {
        log.info("AlipayController - callback/return 执行了....");
        // 同步回调给用户展示信息
        return "redirect:" + AlipayConfig.return_order_url;
    }

    /**
     * 异步回调地址：
     *      这个地址会被调用 共 8次
     *         通知的间隔频率为：4m、10m、10m、1h、2h、6h、15h。
     *  支付宝异步通知返回的数据：https://opendocs.alipay.com/open/203/105286?ref=api
     *  {gmt_create=2024-10-18 11:39:02, charset=utf-8, seller_email=zhuchangqing@atguigu.com,
     *  subject=小米 红米Note10 5G手机 白色   8G;, sign=CuQxj/vf7Zs7RhZ6VtSKdLDMh3V4dyt7qyo/04q941flDXJ3r5vCRdzVXGImRc8/UWDmuc0DcD8iDhL2i88rAAlZxC+3iNqB+NLqwKHnN5x5BRNVf8tRPKJyXGv7RUKsPvJgM+jrqBx5AkWSQw+Zjq/jyg1wO2ADGruGLZhzUw1HpghSkDKetanCgF69JvggF39AXcJHZk7d53FuuMP6MGT8oOfbu4G94EQGddsmwF21o0RUJE+GVKngrVpCwnm1a9EHOmpf9wY/x22UFymrljFET9UvgeIGumSSTRIgEgeu9z6/7idav5IJQG0kRSNJDBQe4U04FpI/PmvR64Yv6A==,
     *  buyer_id=2088502182688796, invoice_amount=0.01, notify_id=2024101801222113902088791461775705,
     *  fund_bill_list=[{"amount":"0.01","fundChannel":"ALIPAYACCOUNT"}], notify_type=trade_status_sync,
     *  trade_status=TRADE_SUCCESS, receipt_amount=0.01, buyer_pay_amount=0.01, app_id=2021001163617452,
     *  sign_type=RSA2, seller_id=2088831489324244, gmt_payment=2024-10-18 11:39:02,
     *  notify_time=2024-10-18 11:39:02, version=1.0,
     *  out_trade_no=8ec0017171bd4ba0b4195add59fce0ef,  订单号
     *  total_amount=0.01,
     *  trade_no=2024101822001488791424343450, //用户和支付宝之间扣款产生的交易流水号。
     *  auth_app_id=2021001163617452,
     *  buyer_logon_id=jls***@163.com, point_amount=0.00}
     * @param paramMap
     * @param request
     * @return
     */
    @RequestMapping("callback/notify")
    @ResponseBody
    public String alipayNotify(@RequestParam Map<String, String> paramMap, HttpServletRequest request) {
        log.info("AlipayController...alipayNotify方法执行了...");
        log.info("AlipayController...alipayNotify方法执行了...paramMap="+paramMap);

        //验签：验证支付宝回传的数据是否被篡改。
        boolean signVerified = false; //调用SDK验证签名
        try {
            signVerified = AlipaySignature.rsaCheckV1(paramMap, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        // true
        if (signVerified) {
            // 交易状态
            String trade_status = paramMap.get("trade_status");

            // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
            if ("TRADE_SUCCESS".equals(trade_status) || "TRADE_FINISHED".equals(trade_status)) {
                // 正常的支付成功，我们应该更新交易记录状态
                paymentInfoService.updatePaymentStatus(paramMap, 2); // 2 支付宝支付    1表示微信支付。
                return "success";  //一定返回给支付宝  "success"这个单词，表示支付流程结束。
            }else{
                return "failure";
            }
        } else {
            // TODO 验签失败则记录异常日志，并在response中返回failure.
            return "failure";
        }
    }
}